package com.universal.aysncCompose.controller;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author austin
 * @data 2022/11/7 18:42
 */
@Slf4j
@RestController
@RequestMapping("/api/supply")
public class SupplyAsyncCompose {

    @Resource
    private ThreadPoolTaskExecutor executorService;

    @SneakyThrows
    @GetMapping(value = "/compose")
    public static String compose() {
        CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
            System.out.println("do something....");
            return "result";
        });
        String result = cf.get(3, TimeUnit.SECONDS);
        log.info("cf结果: {}", result);
        return result;
    }

    @SneakyThrows
    @GetMapping(value = "/composeWithCustomExecutorService")
    public String composeWithCustomExecutorService() {
        CompletableFuture<String> cf = CompletableFuture.supplyAsync(() -> {
            System.out.println("do something....");
            return "result";
        }, executorService);
        String result = cf.get(3, TimeUnit.SECONDS);
        log.info("cf结果: {}", result);
        return result;
    }

    public static void main(String[] args) {
        compose();
    }
}
